<?php
/**
 * @link http://www.tpframe.com/
 * @copyright Copyright (c) 2017 TPFrame Software LLC
 * @author 510974211@qq.com
 * 同步问题请使用锁处理
 */
namespace tpfcore\payment;
use tpfcore\base\Payment;
class Alipay extends Payment{
	protected $gatewayUrl = 'https://openapi.alipay.com/gateway.do';
	protected $appId = null;
	protected $rsaPrivateKey = null;
	protected $alipayrsaPublicKey = null;
	protected $signType ;

	protected $return_url;

	protected $config = [];

	/**
	 * 构造方法，配置应用信息
	 * @param array $token 
	 */
	public function __construct($config=[],$callback=[]){
		//设置SDK类型
		$class = get_class($this);

		$this->Callback=isset($callback['notify_url']) && !empty($callback['notify_url'])?$callback['notify_url']:SITE_PATH."/payment/pay/alipay_notify";		//设置回调地址

		$this->return_url=isset($callback['notify_url']) && !empty($callback['notify_url'])?$callback['notify_url']:SITE_PATH."/payment/pay/alipay_return";		//设置回调地址
	
		$this->Type = strtoupper(substr($class, 0, strlen($class)-3));

		//获取应用配置
		if(empty($config['appId']) || empty($config['rsaPrivateKey']) || empty($config['alipayrsaPublicKey'])){
			throw new \Exception('请先配置好你的参数');
		} else {
			$this->config['gatewayUrl']=$this->gatewayUrl;
			$this->config['sign_type']=empty($config['signType'])?"RSA2":$config['signType'];
			$this->config['charset']=empty($config['charset'])?"UTF-8":$config['charset'];
			$this->config['notify_url']=$this->Callback;
			$this->config['return_url']=$this->return_url;
			$this->config['app_id']=$config['appId'];
			$this->config['merchant_private_key']=$config['rsaPrivateKey'];
			$this->config['alipay_public_key']=$config['alipayrsaPublicKey'];

			$this->appId    = $config['appId'];
			$this->rsaPrivateKey = $config['rsaPrivateKey'];
			$this->alipayrsaPublicKey = $config['alipayrsaPublicKey'];
			!empty($config['signType']) && $this->signType = $config['signType'];
		}
	}

	/*
	* $pay_param	支付配置参数
	* $handle 		支付类别 默认app
	*/
	public function pay($pay_param,$handle="app"){
		$payment_way="pay_".$handle;
		return $this->$payment_way($pay_param);
	}

	/*
		app支付
	*/
	private function pay_app($pay_param){
		$Alipay = new \AlipayTradeAppPayRequest();
		$Alipay->setNotifyUrl($this->Callback);//回调地址
        $Alipay->setBizContent(json_encode($pay_param,JSON_UNESCAPED_UNICODE));

        $orderString = $this->sdkExecute($Alipay);
        if ($orderString == null || $orderString == ''){
        	return [404,'获取orderString失败'];
        }else{
        	return [0,'支付宝sign',["key"=>$orderString]];
        }
	}
	/*
		pc支付
		$pay_param=[
            'body'=>"【TPFrame】钱包充值",        // 商品描述
            'out_trade_no'=>date('Ymdhis').rand(10000,99999),       // 商户订单号 
            'total_amount'=>"1000",            //总金额
            'subject'=>"付款",                  // 商品的标题/交易标题/订单标题/订单关键字等
        ];
        (new Alipay(Core::loadModel("Payment")->getPaymentConfig("alipay",'pc')))->pay($pay_param,"pc");
	*/
	private function pay_pc($pay_param){

		//商户订单号，商户网站订单系统中唯一订单号，必填
	    $out_trade_no = trim($pay_param['out_trade_no']);

	    //订单名称，必填
	    $subject = trim($pay_param['subject']);

	    //付款金额，必填
	    $total_amount = trim($pay_param['total_amount']);

	    //商品描述，可空
	    $body = trim($pay_param['body']);
	    
		//构造参数
		$payRequestBuilder = new \AlipayTradePagePayContentBuilder();
		$payRequestBuilder->setBody($body);
		$payRequestBuilder->setSubject($subject);
		$payRequestBuilder->setTotalAmount($total_amount);
		$payRequestBuilder->setOutTradeNo($out_trade_no);
		$payResponse = new \AlipayTradeService($this->config);

		/**
		 * pagePay 电脑网站支付请求
		 * @param $builder 业务参数，使用buildmodel中的对象生成。
		 * @param $return_url 同步跳转地址，公网可以访问
		 * @param $notify_url 异步通知地址，公网可以访问
		 * @return $response 支付宝返回的信息
	 	*/
		$response = $payResponse->pagePay($payRequestBuilder,$this->config['return_url'],$this->config['notify_url']);

		//输出表单
		die($response);
	}

	/*
		wap支付
		$pay_param=[
            'body'=>"【TPFrame】钱包充值",        // 商品描述
            'out_trade_no'=>date('Ymdhis').rand(10000,99999),       // 商户订单号 
            'total_amount'=>"1000",            //总金额
            'subject'=>"付款",                  // 商品的标题/交易标题/订单标题/订单关键字等
        ];
        (new Alipay(Core::loadModel("Payment")->getPaymentConfig("alipay",'wap')))->pay($pay_param,"wap");
	*/
	private function pay_wap($pay_param){

		//商户订单号，商户网站订单系统中唯一订单号，必填
	    $out_trade_no = trim($pay_param['out_trade_no']);

	    //订单名称，必填
	    $subject = trim($pay_param['subject']);

	    //付款金额，必填
	    $total_amount = trim($pay_param['total_amount']);

	    //商品描述，可空
	    $body = trim($pay_param['body']);

		if (!empty($out_trade_no) && trim($out_trade_no)!=""){
		    //超时时间
		    $timeout_express="1m";
		    $payRequestBuilder = new \AlipayTradeWapPayContentBuilder();
		    $payRequestBuilder->setBody($body);
		    $payRequestBuilder->setSubject($subject);
		    $payRequestBuilder->setOutTradeNo($out_trade_no);
		    $payRequestBuilder->setTotalAmount($total_amount);
		    $payRequestBuilder->setTimeExpress($timeout_express);
		    $payResponse = new \AlipayTradeService($this->config);
		    $response=$payResponse->wapPay($payRequestBuilder,$this->config['return_url'],$this->config['notify_url']);
		    //输出表单
			die($response);
		}else{
			throw new Exception("没有要付款的订单", 1);
		}
	}

	/**
     * 生成用于调用收银台SDK的字符串【支付宝】
     * @param $request
     * @return string
     */
    private function sdkExecute($request) {
        $aop = new \AopClient ();
        $aop->gatewayUrl = $this->gatewayUrl;
        $aop->appId = "2017080908103779";
        $aop->rsaPrivateKey=$this->rsaPrivateKey;
        $aop->alipayrsaPublicKey=$this->alipayrsaPublicKey;
        $aop->signType=$this->signType;
        $aop->apiVersion = "1.0";
        $result = $aop->sdkExecute($request);
        return $result;
    }
}